using System;
using System.Windows;
using System.Windows.Media;

using ICSharpCode.AvalonEdit.Rendering;

namespace ICSharpCode.AvalonEdit.Editing
{
    internal sealed class SelectionLayer : Layer, IWeakEventListener
    {
        private readonly TextArea _textArea;

        public SelectionLayer(TextArea textArea)
            : base(textArea.TextView, KnownLayer.Selection)
        {
            IsHitTestVisible = false;
            _textArea = textArea;
            TextViewWeakEventManager.VisualLinesChanged.AddListener(textView, this);
            TextViewWeakEventManager.ScrollOffsetChanged.AddListener(textView, this);
        }

        bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
        {
            if (managerType == typeof (TextViewWeakEventManager.VisualLinesChanged)
                || managerType == typeof (TextViewWeakEventManager.ScrollOffsetChanged))
            {
                InvalidateVisual();
                return true;
            }
            return false;
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);
            var geoBuilder = new BackgroundGeometryBuilder
                {
                    AlignToMiddleOfPixels = true,
                    CornerRadius = _textArea.SelectionCornerRadius
                };

            foreach (var segment in _textArea.Selection.Segments)
            {
                geoBuilder.AddSegment(textView, segment);
            }

            var geometry = geoBuilder.CreateGeometry();
            if (geometry != null)
            {
                drawingContext.DrawGeometry(_textArea.SelectionBrush, _textArea.SelectionBorder, geometry);
            }
        }
    }
}
